package com.hp.java09_springboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.java09_springboot.pojo.JsonResult;
import com.hp.java09_springboot.pojo.User;
import com.hp.java09_springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

//    @RequestMapping("/users")
//    public String findAll(Model model){
//        List<User> users = userService.list();
//        model.addAttribute("users",users);
//        return "user-list";
//    }

//    @RequestMapping("/users")
//    public String findPage(Model model,@RequestParam(
//            value = "current",required = false,defaultValue = "1") Integer current){
//        Page<User> page = new Page<>(current,10);
//        //传入分页参数，获得分页结果
//        IPage<User> result = userService.getPage(page);
//        model.addAttribute("page",result);
//        return "user-list";
//    }

    @ResponseBody
    @RequestMapping("/users")
    public JsonResult findPage(@RequestParam(
            value = "current",required = false,defaultValue = "1") Integer current){
        try {
            Page<User> page = new Page<>(current, 10);
            //传入分页参数，获得分页结果
            IPage<User> result = userService.getPage(page);
            return new JsonResult(1,"ok",result);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null,null);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(@RequestBody User user){
        userService.save(user);
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String updateUser(@RequestBody User user){
        userService.updateById(user);
        return "ok";
    }

    @ResponseBody
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("id") String id){
        id = id.replace("\"","");
        userService.removeById(id);
        return "ok";
    }

    @GetMapping("/user/{id}")
    public String findById(@PathVariable("id") String id,Model model){
        id = id.replace("\"","");
        User user = userService.getById(id);
        model.addAttribute("user",user);
        return "user-update";
    }
}
